import cv2
from util import public_tools as tool
from util import io_tools as io
from service import recongnize_service as rs
from service import hr_service as hr

# 全局变量
ESC_KEY = 27  # Esc 键的 ASCII 码
ENTER_KEY = 13  # Enter 键的 ASCII 码

def register(code):
    """
    通过摄像头注册员工照片（拍摄3张）并保存到指定路径。

    该函数会启动摄像头，允许用户通过按键控制拍照过程：
    - 按ESC键：取消注册
    - 按Enter键：拍摄并保存照片
    - 成功拍摄3张照片后自动完成注册
    :param code: code (str): 员工特征码（用于命名照片文件
    :return: None
    """
    cameraCapture = cv2.VideoCapture(0, cv2.CAP_DSHOW)  # 获得默认摄像头
    success, frame = cameraCapture.read()  # 读取一帧
    shooting_time = 0  # 拍摄次数
    while success:  # 如果读到有效帧数
        cv2.imshow("register", frame)  # 展示当前画面
        success, frame = cameraCapture.read()  # 再读一帧
        key = cv2.waitKey(1)  # 记录当前用户敲下的按键
        if key == ESC_KEY:  # 如果直接按ESC键
            break  # 停止循环
        if key == ENTER_KEY:  # 如果按Enter键
            # 将当前帧缩放成统一大小
            photo = cv2.resize(frame, dsize=(io.IMG_WIDTH, io.IMG_HEIGHT))
            # 拼接照片名：照片文件夹+特征码+随机数字+图片后缀
            img_name = io.PIC_PATH + str(code) + str(tool.randomNumber(3)) + ".png"
            cv2.imwrite(img_name, photo)  # 保存将图像
            shooting_time += 1  # 拍摄次数递增
            if shooting_time == 3:  # 如果拍完三张照片
                break  # 停止循环
    cv2.destroyAllWindows()  # 释放所有窗体
    cameraCapture.release()  # 释放摄像头
    io.load_employee_pic()  # 让人脸识别服务重新载入员工照片


def clock_in():
    """
    打开摄像头打卡
    :return: 识别到的返回员工name，如果未识别到则返回None
    """
    cameraCapture = cv2.VideoCapture(0, cv2.CAP_DSHOW)  # 获得默认摄像头
    success, frame = cameraCapture.read()  # 读取一帧
    while success and cv2.waitKey(1) == -1:
        cv2.imshow("check in", frame)
        gary = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        if rs.found_face(gary):
            #将当前帧缩放成同意大小
            gary = cv2.resize(gary, (io.IMG_WIDTH, io.IMG_HEIGHT))
            code = rs.recongnise_face(gary)
            if code != -1:
                name = hr.get_name_with_code(code)
                if name != None:
                    cv2.destroyAllWindows()
                    cameraCapture.release()
                    return name
                else:
                    return None
        success, frame = cameraCapture.read()
    cv2.destroyAllWindows()
    cameraCapture.release()